<template>
  <div class="app-container">
    <div class="search-bar">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="公告标题" prop="s_title">
          <el-input v-model="queryParams.s_title" placeholder="关键字" clearable @keyup.enter="handleQuery()" />
        </el-form-item>
        <el-form-item label="状态" prop="show_status">
          <el-select v-model="queryParams.show_status" placeholder="全部" clearable class="!w-[100px]">
            <el-option label="显示" :value="1" />
            <el-option label="隐藏" :value="2" />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleQuery()">
            <template #icon>
              <Search />
            </template>
            搜索
          </el-button>
          <el-button @click="handleResetQuery()">
            <template #icon>
              <Refresh />
            </template>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <div class="flex-x-between mb-10px">
        <div>
          <el-button v-hasPerm="['/admin/content/notice/add']" type="success" icon="plus" @click="handleOpenDialog()">
            新增
          </el-button>
          <el-button :disabled="selectIds.length === 0" v-hasPerm="['/admin/content/notice/del']" type="danger"
            icon="delete" @click="handleDelete()">
            删除
          </el-button>
        </div>
      </div>
      <el-table ref="dataTableRef" v-loading="loading" :data="pageData" highlight-current-row
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column label="公告id" prop="id" width="100" />
        <el-table-column label="排序" prop="sort" width="100" />
        <el-table-column label="标题" prop="title" min-width="200" />
        <el-table-column label="创建时间" align="center" prop="created_at" width="180">
          <template #default="scope">
            {{ formatTimestamp(scope.row.created_at * 1000) }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="状态" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.show_status == 1" type="success">显示</el-tag>
            <el-tag v-else type="info">隐藏</el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" fixed="right" label="操作" width="160">
          <template #default="scope">
            <el-button v-hasPerm="'/admin/content/notice/update'" type="primary" icon="edit" link size="small"
              @click="handleOpenDialog(scope.row.id)">
              编辑
            </el-button>
            <el-button v-hasPerm="['/admin/content/notice/del']" type="danger" icon="delete" link size="small"
              @click="handleDelete(scope.row.id)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-if="total > 0" v-model:total="total" v-model:page="queryParams.page" v-model:limit="queryParams.ps"
        @pagination="handleQuery()" />
    </el-card>

    <!-- 表单 -->
    <el-dialog :close-on-click-modal="false" v-model="dialog.visible" :title="dialog.title" append-to-body
      @close="handleCloseDialog">
      <el-form ref="formRef" :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="formData.title" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input v-model="formData.sort" placeholder="请输入排序" />
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <editor v-model="formData.content" class="border" style="height:500px;" />
        </el-form-item>
        <el-form-item label="是否显示">
          <el-radio-group v-model="formData.show_status">
            <el-radio :value="2" label="不显示" />
            <el-radio :value="1" label="显示" />
          </el-radio-group>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="handleCloseDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "MyNotice",
  inheritAttrs: false,
});

import NoticeAPI, { NoticePageQuery, NoticePageVO } from "@/api/system/notice";
import Editor from "@/components/WangEditor/index.vue";
import { formatTimestamp } from '@/utils/index';

const queryFormRef = ref(ElForm);

const pageData = ref<NoticePageVO[]>([]);

const loading = ref(false);
const total = ref(0);

const queryParams = reactive<NoticePageQuery>({
  page: 1,
  ps: 10,
});

const formRef = ref(ElForm);

// 选中的ID
const selectIds = ref<number[]>([]);


// 选中项发生变化
function handleSelectionChange(selection: any[]) {
  selectIds.value = selection.map((item) => item.id);
}

// 正则验证
const rules = reactive({
  title: [{ required: true, message: "标题不能为空", trigger: "blur" }],
  sort: [{ required: true, message: "排序不能为空", trigger: "blur" }],
  content: [{ required: true, message: "内容不能为空", trigger: "blur" }],
});

const dialog = reactive({
  visible: false,
  title: "新增公告",
});

const formData = reactive<any>({
  show_status: 2
});

// 提交表单（防抖）
const handleSubmit = useDebounceFn(() => {
  formRef.value.validate((valid: boolean) => {
    if (valid) {
      const userId = formData.id;
      loading.value = true;
      if (formData.is_root == 1) {
        formData.role_ids = [];
      }

      if (userId) {
        NoticeAPI.update(formData)
          .then(() => {
            ElMessage.success("修改成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        NoticeAPI.add(formData)
          .then(() => {
            ElMessage.success("新增成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}, 1000);


// 关闭弹窗
function handleCloseDialog() {
  dialog.visible = false;
  formRef.value.resetFields();
  formRef.value.clearValidate();

  formData.id = undefined;
  formData.status = 1;
}

/**
 * 打开弹窗
 *
 * @param id 公告ID
 */
async function handleOpenDialog(id?: number) {
  dialog.visible = true;
  if (id) {
    NoticeAPI.getDetail({ id }).then(res => {
      Object.assign(formData, { ...res.info });
    })
    dialog.title = "修改公告";
  } else {
    dialog.title = "新增公告";
  }
}


/**
 * 删除用户
 *
 * @param id  ID
 */
function handleDelete(id?: number) {
  let userIds = id ? [id] : selectIds.value;
  if (!userIds) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除用户?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    function () {
      loading.value = true;
      NoticeAPI.deleteByIds({ ids: userIds })
        .then(() => {
          ElMessage.success("删除成功");
          handleResetQuery();
        })
        .finally(() => (loading.value = false));
    },
    function () {
      ElMessage.info("已取消删除");
    }
  );
}

/** 查询通知公告 */
function handleQuery() {
  loading.value = true;
  NoticeAPI.getMyNoticePage(queryParams)
    .then((data) => {
      pageData.value = data.data;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

/** 重置通知公告查询 */
function handleResetQuery() {
  queryFormRef.value!.resetFields();
  queryParams.page = 1;
  handleQuery();
}

onMounted(() => {
  handleQuery();
});
</script>
<style scoped lang="scss">
.border {
  border: 1px solid #dcdfe6;
  border-radius: 10rpx;
  overflow: hidden;
}

:deep() {
  .w-e-text-container {
    height: 410px !important;
  }
}
</style>
